﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using Microsoft.AspNet.Identity;
using CaltechSoft.Service.EntityFW.Entity;
using System.Security.Claims;
using Caltech.Service.Common;
using System.Net;

namespace Caltech.Extensions
{
    public class HasAccessAttribute : AuthorizeAttribute
    {
        public Areas Area  { get; set; }

        public HasAccessAttribute(Areas area)
        {
            Area = area;
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var identity = HttpContext.Current.User.Identity;

            if (!Utils.HasAccess(Area))
            {
                return false;
            }

            return base.IsAuthorized(actionContext);
        }
    }

    public class Utils
    {
        public static bool HasAccess(Areas area)
        {
            var identity = HttpContext.Current.User.Identity;

            if (identity.IsAuthenticated)
            {
                var userId = identity.GetUserId();
                var claims = ((ClaimsIdentity)identity).Claims;
                var rolename = claims.FirstOrDefault(c => c.Type == ClaimTypes.Role).Value;
               // var rolename = Roles.Admin.ToString();
                var roleManager = System.Web.Mvc.DependencyResolver.Current.GetService(typeof(RoleManager<Role>)) as RoleManager<Role>;
                var areas = roleManager.FindByName(rolename).Areas;

                foreach (Enum value in Enum.GetValues(area.GetType()).Cast<Areas>().Where(item => area.HasFlag(item)))
                {
                    if (areas.GetValueOrDefault().HasFlag(value))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}